package com.ajl.wx.module.oss.service.impl;

import com.ajl.wx.config.WebApplicationProperties;
import com.ajl.wx.module.oss.service.IOssService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@Service
public class OssServiceImpl implements IOssService {
    @Autowired
    WebApplicationProperties webApplicationProperties;

    @Override
    public void saveFile(String fileName, InputStream inputStream) {
        this.doSave(fileName,inputStream);
    }
    @Override
    public void saveFile(String fileName, File file) {
        try {
            this.doSave(fileName,new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    private void doSave(String fileName, InputStream inputStream){
        OSS oss = createOSS();
        PutObjectRequest putObjectRequest = new PutObjectRequest(webApplicationProperties.getBucketName(), fileName, inputStream);
        oss.putObject(putObjectRequest);
        oss.shutdown();
    }
    private OSS createOSS(){
        OSS ossClient = new OSSClientBuilder().build(webApplicationProperties.getEndpoint(),
                webApplicationProperties.getAccessKeyId(),
                webApplicationProperties.getAccessKeySecret());
        return ossClient;
    }
}
